package com.ww.springboot.boot.algorithm.leetcode1;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-05-30 10:04
 */
public class CF1022从根到叶的二进制数之和 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1, new TreeNode(0, new TreeNode(0), new TreeNode(1)), new TreeNode(1, new TreeNode(0), new TreeNode(1)));
        System.out.println(sumRootToLeaf(root));
    }


    /**
     * 广度遍历 解题错误:每个节点不能只计算一次
     *
     * 改动:直接从上往下累加 每遍历一层则将之前的结果 >> 1
     *
     * @param root
     * @return
     */
    public static int sumRootToLeaf(TreeNode root) {
        int[] array = new int[32];
        int index = 0;

        Queue<TreeNode> treeNodeStack = new LinkedBlockingQueue<>();
        treeNodeStack.add(root);
        treeNodeStack.add(new TreeNode(-1));
        int count = 0;
        while (!treeNodeStack.isEmpty()) {
            TreeNode treeNode = treeNodeStack.poll();
            if (treeNode.val == -1) {
                array[index] = count;
                count = 0;
                index++;
                if (treeNodeStack.isEmpty()) {
                    break;
                }
                treeNodeStack.add(new TreeNode(-1));
                continue;
            } else {
                count += treeNode.val;
                if (treeNode.left != null) {
                    treeNodeStack.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    treeNodeStack.add(treeNode.right);
                }
            }
        }

        int total = 0;
        for (int i = 0; i < index; i++) {
            total += array[i] * Math.pow(2, index - i - 1);
        }
        return total;
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
